import React from 'react';
import { GetServerSideProps } from 'next';
import { ParsedUrlQuery } from 'querystring';
import { out } from '@a2r/telemetry';
import AuthLayout from '../../src/components/layout/AuthLayout';
import Splash from '../../src/components/pages/auth/Splash';
import ResetPassword from '../../src/components/pages/auth/ResetPassword';
import { ResetPasswordProps } from '../../src/model/components/resetPassword';
import getUserByPasswordToken from '../../src/utils/api/user/getUserByPasswordToken';

const showSplash = false;
const showResetPassword = true;

let layoutClass = 'forgotPassword';

if (showSplash) {
  layoutClass = 'splash';
}

const resetPassword: React.FC<ResetPasswordProps> = ({ email, token }) => (
  <AuthLayout
    title="Olvidé mi contraseña"
    mainClassName={layoutClass}
    splash={showSplash}
    auth
  >
    {showSplash ? <Splash /> : null}
    {showResetPassword && !showSplash ? (
      <ResetPassword email={email} token={token} />
    ) : null}
  </AuthLayout>
);

interface PageProps extends ParsedUrlQuery {
  token: string;
}

export const getServerSideProps: GetServerSideProps<
  ResetPasswordProps,
  PageProps
> = async (ctx) => {
  const { token } = ctx.params;

  const { ok, error, data: email } = await getUserByPasswordToken(token);

  if (!ok) {
    out.error(`Error getting user by password token: ${error}`);
    return {
      redirect: {
        destination: `/`,
        permanent: true,
      },
    };
  }

  return {
    props: {
      email,
      token,
    },
  };
};
export default resetPassword;
